package cc.catface.service.app.article;

import cc.catface.common.output.ResultBody;
import cc.catface.dao.app.mapper.article.*;
import cc.catface.dao.app.pojo.article.dto.ApArticleListInputDTO;
import cc.catface.dao.app.pojo.article.pojo.ApArticle;
import cc.catface.dao.app.pojo.article.pojo.ApArticleContent;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class ApArticleServiceImpl implements ApArticleService {
    @Autowired
    private ApArticleMapper articleMapper;
    @Autowired
    private ApArticleMapperServiceImpl articleMapperService;
    @Autowired
    private ApArticleContentMapperServiceImpl articleContentMapperService;

    @Override
    public ResultBody add(ApArticle article) {
        article.setPublishTime(new Date());
        articleMapperService.save(article);
        //保存文章详细内容
        log.info("文章插入成功, ID:{}, 详细内容:{}", article.getId(), article.getContent());
        ApArticleContent apArticleContent = new ApArticleContent();
        apArticleContent.setArticleId(article.getId());
        apArticleContent.setContent(article.getContent());
        articleContentMapperService.save(apArticleContent);
        return ResultBody.success();
    }

    //文章列表
    @Override
    public ResultBody list(ApArticleListInputDTO in) {
        if (in == null) throw new NullPointerException("请检查参数！");

        QueryWrapper<ApArticle> wrapper = new QueryWrapper<>();
        wrapper.eq("channel_id", in.getChannelId());
        //List<ApArticle> list = articleMapperService.list(wrapper);
        List<ApArticle> list = articleMapper.selectPage(new Page<>(in.getPage(), in.getPageSize()), wrapper).getRecords();
        return ResultBody.success(list);
    }

    //文章内容(根据文章id)
    @Override
    public ResultBody getContent(long id) {
        //查询文章详细内容
        QueryWrapper<ApArticleContent> wrapper = new QueryWrapper<>();
        wrapper.eq("article_id", id);
        String content = articleContentMapperService.getOne(wrapper).getContent();
        //文章阅读量加1
        ApArticle byId = articleMapperService.getById(id);
        if (byId != null) {
            Integer views = byId.getViews();
            views = views + 1;
            byId.setViews(views);
            articleMapperService.updateById(byId);
        }
        return ResultBody.success(content);
    }

    @Override
    public ResultBody update(ApArticle article) {
        return null;
    }
}
